package DAO.imp;
import DAO.BaseExpressDao;
import com.Express.util.DruidUtil;
import com.bean.Express;
import Exception.DuplicateCodeException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExpressDaoMysql implements BaseExpressDao {
    /**
     * 查询全部快递（总数+新增），待取件快递（总数+新增）
     */
    public static final String SQL_CONSOLE = "SELECT " +
            "COUNT(ID) data1_size," +
            "COUNT(TO_DAYS(INTIME)=TO_DAYS(NOW()) OR NULL) data1_day," +
            "COUNT(STATUS=0 OR NULL) data2_size," +
            "COUNT(TO_DAYS(INTIME)=TO_DAYS(NOW()) AND STATUS=0 OR NULL) data2_day from EXPRESS";
    /**
     * 查询数据库中所有的快递信息
     */
    public static final String SQL_FIND_ALL = "SELECT * FROM EXPRESS";
    /**
     * 分页查询数据库中所有快递信息
     */
    public static final String SQL_FIND_LIMIT = "SELECT * FROM EXPRESS LIMIT ?,?";
    /**
     * 通过取件码查询快递信息
     */
    public static final String SQL_FIND_BY_CODE = "SELECT * FROM EXPRESS WHERE CODE=?";
    /**
     * 通过快递单号查询快递信息
     */
    public static final String SQL_FIND__BY_NUMBER = "SELECT * FROM EXPRESS WHERE NUMBER=?";
    /**
     * 通过录入手机号查询快递信息
     */
    public static final String SQL_FIND_BY_SYSPHONE = "SELECT * FROM EXPRESS WHERE SYSPHONE=?";
    /**
     * 通过用户手机号查询快递信息
     */
    public static final String SQL_FIND_BY_USERPHONE = "SELECT * FROM EXPRESS WHERE USERPHONE=?";
    /**
     * 通过用户手机号查询用户的未取件快递
     */
    public static final String SQL_FIND_BY_USERPHONE_And_Status = "SELECT * FROM EXPRESS WHERE USERPHONE=? AND STATUS=?";
    /**
     * 录入快递
     */
    public static final String SQL_INSERT = "INSERT INTO EXPRESS(NUMBER,USERNAME,USERPHONE,COMPANY,CODE,INTIME,STATUS,SYSPHONE) VALUES(?,?,?,?,?,NOW(),0,?)";
    /**
     * 修改快递
     */
    public static final String SQL_UPDATE = "UPDATE EXPRESS SET NUMBER=?,USERNAME=?,COMPANY=?,STATUS=? WHERE ID=?";
    /**
     * 快递状态码修改（取件）
     */
    public static final String SQL_UPDATE_STATUS = "UPDATE EXPRESS SET STATUS=1,OUTTIME=NOW(),CODE=NULL WHERE CODE=?";
    /**
     * 快递的删除
     */
    public static final String SQL_DELETE = "DELETE FROM EXPRESS WHERE ID=?";

    /**
     * 用于查询数据库中的全部快递（总数，当日新增）
     * 待取件快递（总数，当日新增）
     *
     * @return [{size:总数, day:新增},{size:总数, day:新增}]
     */
    @Override
    public List<Map<String, Integer>> console() {
        ArrayList<Map<String, Integer>> data = new ArrayList<>();
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;

        try {
            state = conn.prepareStatement(SQL_CONSOLE);
            result = state.executeQuery();
            if (result.next()){
                int data1_size = result.getInt("data1_size");
                int data1_day = result.getInt("data1_day");

                int data2_size = result.getInt("data2_size");
                int data2_day = result.getInt("data2_day");

                Map<String,Integer> data1 = new HashMap<>();
                data1.put("data1_size",data1_size);
                data1.put("data1_day",data1_day);

                Map<String,Integer> data2 = new HashMap<>();
                data2.put("data2_size",data2_size);
                data2.put("data2_day",data2_day);

                data.add(data1);
                data.add(data2);

            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }

        return data;
    }

    /**
     * 查询所有快递
     *
     * @param limit      是否分页的标记，true：分页，false：查询所有
     * @param offset     sql语句的起始索引
     * @param pageNumber 每一页查询的数量
     * @return 快递的集合
     */
    @Override
    public List<Express> findAll(boolean limit, int offset, int pageNumber) {
        ArrayList<Express> data = new ArrayList<>();
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;

        try {
            if (limit){
                state = conn.prepareStatement(SQL_FIND_LIMIT);
                state.setInt(1,offset);
                state.setInt(2,pageNumber);
            }else {
                state = conn.prepareStatement(SQL_FIND_ALL);
            }
            result = state.executeQuery();

            while (result.next()){
                int id = result.getInt("id");
                String number = result.getString("number");
                String username = result.getString("username");
                String userPhone = result.getString("userPhone");
                String company = result.getString("company");
                String code = result.getString("code");
                java.sql.Timestamp inTime = result.getTimestamp("inTime");
                java.sql.Timestamp outTime = result.getTimestamp("outTime");
                int status = result.getInt("status");
                String sysPhone = result.getString("sysPhone");
                //Express e = new Express(id, number, username, userPhone, company, code, inTime, outTime, status, sysPhone);
                Express e = new Express();
                e.setId(id);
                e.setCode(code);
                e.setCompany(company);
                e.setInTime(inTime);
                e.setOutTime(outTime);
                e.setNumber(number);
                e.setStatus(status);
                e.setSysPhone(sysPhone);
                e.setUsername(username);
                e.setUserPhone(userPhone);
                System.out.println(e);
                data.add(e);
            }
            return data;
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }

    /**
     * 根据快递单号查询快递信息
     *
     * @param number 单号
     * @return 查询的快递信息，单号不存在时返回null
     */
    @Override
    public Express findByNumber(String number) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;

        try {
            state = conn.prepareStatement(SQL_FIND__BY_NUMBER);
            state.setString(1, number);
            result = state.executeQuery();

            if (result.next()){
                int id = result.getInt("id");
                String username = result.getString("username");
                String userPhone = result.getString("userPhone");
                String company = result.getString("company");
                String code = result.getString("code");
                java.sql.Timestamp inTime = result.getTimestamp("inTime");
                java.sql.Timestamp outTime = result.getTimestamp("outTime");
                int status = result.getInt("status");
                String sysPhone = result.getString("sysPhone");
                //Express e = new Express(id, number, username, userPhone, company, code, inTime, outTime, status, sysPhone);
                Express e = new Express();
                e.setId(id);
                e.setCode(code);
                e.setCompany(company);
                e.setInTime(inTime);
                e.setOutTime(outTime);
                e.setNumber(number);
                e.setStatus(status);
                e.setSysPhone(sysPhone);
                e.setUsername(username);
                e.setUserPhone(userPhone);
                System.out.println(e);
                return e;
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return null;
    }

    /**
     * 根据快递单号查询快递信息
     *
     * @param code 取件码
     * @return 查询的快递信息，取件码不存在时返回null
     */
    @Override
    public Express findByCode(String code) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;

        try {
            state = conn.prepareStatement(SQL_FIND_BY_CODE);
            state.setString(1, code);
            result = state.executeQuery();
            if (result.next()){
                int id = result.getInt("id");
                String number = result.getString("number");
                String username = result.getString("username");
                String userPhone = result.getString("userPhone");
                String company = result.getString("company");
                java.sql.Timestamp inTime = result.getTimestamp("inTime");
                java.sql.Timestamp outTime = result.getTimestamp("outTime");
                int status = result.getInt("status");
                String sysPhone = result.getString("sysPhone");
                Express e = new Express();
                //id, number, username, userPhone, company, code, inTime, outTime, status, sysPhone);
                e.setId(id);
                e.setNumber(number);
                e.setUserPhone(userPhone);
                e.setUsername(username);
                e.setCompany(company);
                e.setCode(code);
                e.setInTime(inTime);
                e.setOutTime(outTime);
                e.setStatus(status);
                e.setSysPhone(sysPhone);
                return e;
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return null;
    }

    /**
     * 根据用户手机号查询所有快递
     *
     * @param userPhone 手机号
     * @return 查询的快递信息，手机号不存在时返回null
     */
    @Override
    public List<Express> findByUserPhone(String userPhone) {
        ArrayList<Express> data = new ArrayList<>();
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;

        try {
            state = conn.prepareStatement(SQL_FIND_BY_USERPHONE);
            state.setString(1,userPhone);
            result = state.executeQuery();
            while (result.next()){
                int id = result.getInt("id");
                String number = result.getString("number");
                String username = result.getString("username");
                String company = result.getString("company");
                String code = result.getString("code");
                java.sql.Timestamp inTime = result.getTimestamp("inTime");
                java.sql.Timestamp outTime = result.getTimestamp("outTime");
                int status = result.getInt("status");
                String sysPhone = result.getString("sysPhone");
                Express e = new Express();
                //(id, number, username, userPhone, company, code, inTime, outTime, status, sysPhone);
                e.setId(id);
                e.setNumber(number);
                e.setUserPhone(userPhone);
                e.setCompany(company);
                e.setCode(code);
                e.setInTime(inTime);
                e.setOutTime(outTime);
                e.setStatus(status);
                e.setSysPhone(sysPhone);
                data.add(e);
            }
            return data;
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }

    @Override
    public List<Express> findByUserPhoneAndStatus(String userPhone, int status) {
        ArrayList<Express> data = new ArrayList<>();
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;

        try {
            state = conn.prepareStatement(SQL_FIND_BY_USERPHONE_And_Status);
            state.setString(1,userPhone);
            state.setInt(2,status);
            result = state.executeQuery();
            while (result.next()){
                int id = result.getInt("id");
                String number = result.getString("number");
                String username = result.getString("username");
                String company = result.getString("company");
                String code = result.getString("code");
                java.sql.Timestamp inTime = result.getTimestamp("inTime");
                Timestamp outTime = result.getTimestamp("outTime");
                String sysPhone = result.getString("sysPhone");
                Express e = new Express();
                //id, number, username, userPhone, company, code, inTime, outTime, status, sysPhone);
                 e.setId(id);
                 e.setNumber(number);
                 e.setUsername(username);
                 e.setUserPhone(userPhone);
                 e.setCompany(company);
                 e.setCode(code);
                 e.setInTime(inTime);
                 e.setOutTime(outTime);
                 e.setStatus(status);
                 e.setSysPhone(sysPhone);
                data.add(e);
            }
            return data;
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }

    /**
     * 根据录入人手机号查询录入的所有记录
     *
     * @param sysPhone 手机号
     * @return 查询的快递信息，手机号不存在时返回null
     */
    @Override
    public List<Express> findBySysPhone(String sysPhone) {
        ArrayList<Express> data = new ArrayList<>();
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;

        try {
            state = conn.prepareStatement(SQL_FIND_BY_SYSPHONE);
            state.setString(1,sysPhone);
            result = state.executeQuery();

            while (result.next()){
                int id = result.getInt("id");
                String number = result.getString("number");
                String username = result.getString("username");
                String userPhone = result.getString("userPhone");
                String company = result.getString("company");
                String code = result.getString("code");
                java.sql.Timestamp inTime = result.getTimestamp("inTime");
                java.sql.Timestamp outTime = result.getTimestamp("outTime");
                int status = result.getInt("status");
                Express e = new Express(id, number, username, userPhone, company, code, inTime, outTime, status, sysPhone);
                data.add(e);
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }

    /**
     * 快递的录入
     * INSERT INTO EXPRESS(NUMBER,USERNAME,USERPHONE,COMPANY,CODE,INTIME,STATUS,SYSPHONE) VALUES(?,?,?,?,?,NOW(),0,?)
     * @param e 要录入的对象
     * @return 录入的结果
     */
    @Override
    public boolean insert(Express e) throws  DuplicateCodeException{

        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_INSERT);

            state.setString(1,e.getNumber());
            state.setString(2,e.getUsername());
            state.setString(3,e.getUserPhone());
            state.setString(4,e.getCompany());
            state.setString(5,e.getCode());
            state.setString(6,e.getSysPhone());

            return (state.executeUpdate() > 0);
        } catch (SQLException e1) {
            if (e1.getMessage().endsWith("for key 'code'")){
                // 是因为取件码重复而出现了异常
                DuplicateCodeException e2 = new DuplicateCodeException(e1.getMessage());
                throw e2;
            }else {
                e1.printStackTrace();
            }
        }finally {
            DruidUtil.close(conn,state,null);
        }

        return false;
    }

    /**
     * 快递的修改
     * UPDATE EXPRESS SET NUMBER=?,USERNAME=?,COMPANY=?,STATUS=? WHERE ID=?
     * @param id         要修改的快递id
     * @param newExpress 新的快递对象（number, company, username, userPhone）
     * @return 修改的结果
     */
    @Override
    public boolean update(int id, Express newExpress) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;

        try {
            state = conn.prepareStatement(SQL_UPDATE);
            state.setString(1,newExpress.getNumber());
            state.setString(2,newExpress.getUsername());
            state.setString(3,newExpress.getCompany());
            state.setInt(4,newExpress.getStatus());
            state.setInt(5,id);

            return state.executeUpdate() > 0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn, state, null);
        }
        return false;
    }

    /**
     * 更改快递状态为1，表示取件完成
     * UPDATE EXPRESS SET STATUS=1 WHERE CODE=?
     * @param code 要取件的取件码
     * @return 修改的结果
     */
    @Override
    public boolean updateStatus(String code) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_UPDATE_STATUS);
            state.setString(1,code);
            return state.executeUpdate() > 0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn, state, null);
        }
        return false;
    }

    /**
     * 根据id，删除单个快递信息
     *
     * @param id 要删除的快递信息
     * @return 删除结果
     */
    @Override
    public boolean delete(int id) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_DELETE);
            state.setInt(1,id);
            return state.executeUpdate() > 0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn, state, null);
        }
        return false;
    }
}
